package tools;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

//import bean.PatientPrelog;

/**
 * Created by TJ on 2016/3/19.
 */
public class GsonTools {
    public static final Gson GSON = new Gson();

    /**
     * 将对象转换为JSON字符串
     * @param src
     * @return
     */
    public static String toJson(Object src) {
        return GSON.toJson(src);
    }

    /**
     * 将JSON传转换为指定对象
     * @param res
     * @param clazz
     * @param <T>
     * @return
     * @throws AppException
     */
    public static <T> T parse(String res, Class<T> clazz) throws AppException {
        try {
            return GSON.fromJson(res, clazz);
        } catch (Exception e) {
            Logger.i(e);
            throw AppException.json(e);
        }
    }

    /**
     * 将JSON传转换为Map<String, String>
     * @param res
     * @return 可能会为null
     * @throws AppException
     */
    public static Map<String, String> parseToMap(String res) throws AppException {
        Type mapType = new TypeToken<Map<String, String>>(){}.getType();
        try {
            return GSON.fromJson(res, mapType);
        } catch (Exception e) {
            Logger.i(e);
            throw AppException.json(e);
        }
    }

    /**
     * 将JSON传转换为List<String[]>
     * @param res
     * @return 可能会为null
     * @throws AppException
     */
    public static List<String[]> parseToListArr(String res) throws AppException {
        Type listType = new TypeToken<String[]>(){}.getType();
        try {
            return GSON.fromJson(res, listType);
        } catch (Exception e) {
            Logger.i(e);
            throw AppException.json(e);
        }
    }
    /**=======================================================
     * 将JSON传转换为List<Object>
     * @param res
     * @return 可能会为null
     * @throws AppException
     * Gson gson =  new Gson();
    List<ConfigMealTime> list = gson.fromJson(res, new TypeToken<List<ConfigMealTime>>(){}.getType());
    Object obj = (Object) list;
     */
    public static <T>  List<T> parseToList(String res,Class<T[]> clazz) throws AppException {
        try {
            T[] arr = new Gson().fromJson(res, clazz);
            return Arrays.asList(arr);
        } catch (Exception e) {
            Logger.i(e);
            throw AppException.json(e);
        }
    }

    /**
     * 将JSON传转换为List<PatientPrelog>
     * @param res
     * @return
     * @throws AppException
     */
//    public static List<PatientPrelog> parseToYYList(String res) throws AppException {
//        Type listType = new TypeToken<List<PatientPrelog>>(){}.getType();
//        try {
//            return GSON.fromJson(res, listType);
//        } catch (Exception e) {
//            Logger.i(e);
//            throw AppException.json(e);
//        }
//    }
}
